package org.example.l0;

import org.junit.jupiter.api.Test;

import java.util.stream.IntStream;

public class minDistance {

    @Test
    void minDistance() {
        minDistance("horse", "ros");
    }

    public int minDistance(String word1, String word2) {
        int len1 = word1.length(), len2 = word2.length();
        int[][] dp = new int[len1 + 1][len2 + 1];
        IntStream.rangeClosed(0, len1).forEach(n -> dp[n][0] = n);
        IntStream.rangeClosed(0, len2).forEach(n -> dp[0][n] = n);

        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j- 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                    continue;
                }

                int v1 = dp[i - 1][j];
                int v2 = dp[i - 1][j - 1];
                int v3 = dp[i][j - 1];
                int min = IntStream.of(v1, v2, v3).min().getAsInt();
                dp[i][j] = min + 1;
            }
        }

        return dp[len1][len2];
    }
}
